﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using XcoAppSpaces.Contracts.Logging;
using XcoAppSpaces.Core;
using XcoAppSpaces.Core.Ports;
using System.Threading;
using System.Threading.Tasks;

namespace test.XcoAppSpaces.Core
{
	[TestClass]
	public class testDirectPortHosting
	{
		[TestMethod]
		public void TestPublishPort()
		{
			XcoLoggerFactory.CreateInstance = _ => new DebugLogger();
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000"),
				space2 = new XcoAppSpace("tcp.port=8001"))
			{
				var port = new Port<int>();
				space1.RunWorker(port);

				var remotePort = space2.ConnectWorker<Port<int>>("localhost:8000");
				
				remotePort.Post(1);
				Assert.AreEqual(1, port.Receive(1000).Result);
			}
		}

		[TestMethod]
		public void TestPublishPortWithName()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000"),
				space2 = new XcoAppSpace("tcp.port=8001"))
			{
				var port = new Port<int>();
				space1.RunWorker(port, "myIntPort");

				var remotePort = space2.ConnectWorker<Port<int>>("localhost:8000/myIntPort");

				remotePort.Post(1);
				Assert.AreEqual(1, port.Receive(1000).Result);
			}
		}

		[TestMethod]
		public void TestPublishPortSet()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000"),
				space2 = new XcoAppSpace("tcp.port=8001"))
			{
				var portSet = new PortSet<int, string>();
				space1.RunWorker(portSet);

				var remotePortSet = space2.ConnectWorker<PortSet<int, string>>("localhost:8000");

				remotePortSet.Post(1);
				remotePortSet.Post("test");
				Assert.AreEqual(1, portSet.P0.Receive(1000).Result);
				Assert.AreEqual("test", portSet.P1.Receive(1000).Result);
			}
		}

		[TestMethod]
		public void TestPublishPortSetWithName()
		{
			using (XcoAppSpace space1 = new XcoAppSpace("tcp.port=8000"),
				space2 = new XcoAppSpace("tcp.port=8001"))
			{
				var portSet = new PortSet<int, string>();
				space1.RunWorker(portSet, "myPortSet");

				var remotePortSet = space2.ConnectWorker<PortSet<int, string>>("localhost:8000/myPortSet");

				remotePortSet.Post(1);
				remotePortSet.Post("test");
				Assert.AreEqual(1, portSet.P0.Receive(1000).Result);
				Assert.AreEqual("test", portSet.P1.Receive(1000).Result);
			}
		}
	}
}
